using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace CMSWeb.Utility.Difference.DataSources
{
	public class TextFile
	{
		protected TextLine[] _lines;

		protected bool _ignoreLeadingWhiteSpace;
		protected bool _ignoreTrailingWhiteSpace;
		protected bool _caseInsensitive;

		public TextFile(string filename)
			: this(filename, false, false, false)
		{
		}

		public TextFile(Stream fileStream)
			: this(fileStream, false, false, false)
		{
		}

		public TextFile(bool ignoreLeadingWhiteSpace, bool ignoreTrailingWhiteSpace, bool caseInsensitive)
			: this("", false, false, false)
		{
		}

		public TextFile(string filename, bool ignoreLeadingWhiteSpace, bool ignoreTrailingWhiteSpace, bool caseInsensitive)
		{
			_ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace;
			_ignoreTrailingWhiteSpace = ignoreTrailingWhiteSpace;
			_caseInsensitive = caseInsensitive;

			if ( !String.IsNullOrEmpty(filename) )
			{
				FileStream stream = new FileStream(filename, FileMode.Open);
				LoadStream(stream);
			}
		}

		public TextFile(Stream fileStream, bool ignoreLeadingWhiteSpace, bool ignoreTrailingWhiteSpace, bool caseInsensitive)
		{
			_ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace;
			_ignoreTrailingWhiteSpace = ignoreTrailingWhiteSpace;
			_caseInsensitive = caseInsensitive;

			LoadStream(fileStream);
		}


		public void LoadStream(Stream fileStream)
		{
			StreamReader sr = new StreamReader(fileStream);

			List<TextLine> lines = new List<TextLine>();
			string line;
			while ( ( line = sr.ReadLine() ) != null )
			{
				TextLine tl = new TextLine(line, _ignoreLeadingWhiteSpace, _ignoreTrailingWhiteSpace, _caseInsensitive);
				lines.Add(tl);
			}

			_lines = lines.ToArray();
		}

		protected void UpdateLines()
		{
			if ( _lines == null )
				return;

			for ( int i = 0; i < _lines.Length; i++ )
			{
				_lines[i].Updating = true;

				_lines[i].CaseSensitive = _caseInsensitive;
				_lines[i].IgnoreLeadingWhiteSpace = _ignoreLeadingWhiteSpace;
				_lines[i].IgnoreTrailingWhiteSpace = _ignoreTrailingWhiteSpace;

				_lines[i].Updating = false;
			}
		}

		public bool IgnoreLeadingWhiteSpace
		{
			get { return _ignoreLeadingWhiteSpace; }
			set { _ignoreLeadingWhiteSpace = value; }
		}

		public bool IgnoreTrailingWhiteSpace
		{
			get { return _ignoreTrailingWhiteSpace; }
			set { _ignoreTrailingWhiteSpace = value; }
		}

		public bool CaseSensitive
		{
			get { return _caseInsensitive; }
			set { _caseInsensitive = value; }
		}
	}
}
